package fr.univ.lr.icone.gui;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.Date;
import java.util.HashMap;

import javax.swing.BorderFactory;
import javax.swing.JPanel;

import fr.univ.lr.icone.gui.zonerender.ColorOpinionMapping;

/**
 * Represents the drawing area (agents will be represented on it)
 * 
 * @author Elian ORIOU
 * 
 */

public class DrawingZone extends JPanel implements IDrawingZone {

	private static final long serialVersionUID = 1L;

	private HashMap<Point, Color> points;
	private int AGENT_DIAMETER_X;
	private int AGENT_DIAMETER_Y;
	private int size;

	public DrawingZone(int n) {
		super();
		this.size = n;
		this.points = new HashMap<Point, Color>();
		init();
	}

	/**
	 * Component initialization method
	 */

	private void init() {
		this.setBorder(BorderFactory.createLineBorder(Color.black));
	}

	/**
	 * Component painting method
	 */

	@Override
	public void paint(Graphics g) {
		super.paint(g);

		/* Drawing Grid on x axis */
		int xspace = getWidth() / size;
		for (int i = 0; i < getWidth(); i = i + xspace) {
			g.drawLine(i, 0, i, getWidth());
		}

		/* Drawing Grid on y axis */
		int yspace = getHeight() / size;
		for (int i = 0; i < getHeight(); i = i + yspace) {
			g.drawLine(0, i, getHeight() + 40, i);
		}

		for (Point p : points.keySet()) {
			Color c = points.get(p);
			g.setColor(c);
			g.fillOval(p.x, p.y, AGENT_DIAMETER_X, AGENT_DIAMETER_Y);
			g.setColor(Color.BLACK);
		}
	}

	/**
	 * Adds an agent to the grid at the position defined by the agent
	 * 
	 * @param a
	 *            the agent to add to the grid
	 */

	public void addAgent(int opinion, Point position) {

		AGENT_DIAMETER_X = getWidth() / size;
		AGENT_DIAMETER_Y = getHeight() / size;

		Point newPosition = convertDivToPixel(position);

		Color color = ColorOpinionMapping.getColor(opinion);
		points.put(newPosition, color);

		repaint();
	}

	/**
	 * Converts division points (in the grid) to pixel value
	 * 
	 * @param divPosition
	 * @return
	 */

	private Point convertDivToPixel(Point divPosition) {
		int posX = divPosition.x * (getWidth() / size);
		int posY = divPosition.y * (getHeight() / size);
		return new Point(posX, posY);
	}

	/**
	 * Removes an agent
	 * 
	 * @param position
	 */

	public void removeAgent(Point position) {
		points.remove(convertDivToPixel(position));
		log("Removing agent at " + position);
	}

	/**
	 * Log method for test
	 * 
	 * @param message
	 *            the message to log
	 */

	private void log(String message) {
		Date d = new Date();
		System.out.println("[LOG : " + d.toString() + "] :: " + message);
	}
}